import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:pcp/widgets/signature_painter.dart';
import 'package:pcp/core/draw_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../common/config/config.dart';

class DrawPage extends StatefulWidget {
  @override
  _DrawPageState createState() => _DrawPageState();
}

class _DrawPageState extends State<DrawPage> {
  DrawProvider _provider = DrawProvider();
  bool boardShow = true;
  var dio = Dio();
  var mediaIdList = [];
  var mediaList = [];
  var comments = [];
  var img;
  bool commentShow = false;
  TextEditingController commentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(
        child: _mediaView(),
      ),
      body: ChangeNotifierProvider.value(
        value: _provider,
        child: Consumer<DrawProvider>(
          builder: (context, drawProvider, _) {
            return Container(
              color: Color(0x18262B33),
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: Stack(
                      children: [
                        Container(
                          color: Colors.black,
                          child: img == null
                              ?  SizedBox(
                            width: 1000,
                            child: Center(
                              child: CircularProgressIndicator(color: Colors.black),
                            ),
                          )
                              : Image.memory(img),
                        ),
                        // Text(drawProvider.points.length.toString()),
                        GestureDetector(
                          //手势探测器，一个特殊的widget，想要给一个widge添加手势，直接用这货包裹起来
                          onPanUpdate: (DragUpdateDetails details) {
                            //按下
                            RenderBox referenceBox = context.findRenderObject();
                            Offset localPosition = referenceBox
                                .globalToLocal(details.globalPosition);
                            drawProvider.sendDraw(localPosition);
                          },
                          onPanEnd: (DragEndDetails details) {
                            drawProvider.sendDrawNull();
                          }, //抬起来
                        ),
                        CustomPaint(
                            painter: SignaturePainter(drawProvider.pointsList)
                        ),
                        Offstage(
                          offstage: !commentShow,
                          child: Align(
                              alignment: Alignment.centerRight,
                              child: Container(
                                width: 250,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    IconButton(
                                      icon: Icon(Icons.navigate_next),
                                      color: Colors.blue,
                                      onPressed: (){
                                        setState(() {
                                          commentShow = !commentShow;
                                        });},
                                    ),
                                    Offstage(
                                        offstage: !commentShow,
                                        child: Opacity(
                                          opacity: 0.9,
                                          child: Container(
                                            width: 200,
                                            decoration: BoxDecoration(
                                              color: Colors.black54,
                                            ),
                                            child: Column(
                                              children: [
                                                Flexible(
                                                  child: ListView.builder(
                                                      itemCount: comments.length,
                                                      itemBuilder: (context, int index) {
                                                        return Container(
                                                          decoration: BoxDecoration(
                                                            border: Border(bottom: Divider.createBorderSide(context, color: Colors.black26, width: 1)),
                                                          ),
                                                          padding: EdgeInsets.only(bottom: 10),
                                                          child: ListTile(
                                                            contentPadding: EdgeInsets.symmetric(horizontal: 10.0),
                                                            dense: true,
                                                            leading: new CircleAvatar(
                                                              backgroundImage: new NetworkImage(
                                                                  Config.BASE_URL + "/user/getProfilePhoto?sex=male"
                                                              ),
                                                            ),
                                                            title: Text(
                                                              comments[index]['content'],
                                                              style: TextStyle(color: Colors.white),
                                                            ),
                                                            subtitle: Text(
                                                              comments[index]['user']['userName'] + "\n" + (comments[index]['createTime'] != '' ? comments[index]['createTime'] : comments[index]['updateTime']),
                                                              style: TextStyle(color: Colors.white),
                                                            ),
                                                          ),
                                                        );
                                                      }),
                                                ),
                                                Container(
                                                  height: 70,
                                                  padding: EdgeInsets.only(left: 10, right: 10, top: 10),
                                                  decoration: BoxDecoration(
                                                    color: Colors.black54
                                                  ),
                                                  child: TextField(
                                                    controller: commentController,
                                                    maxLines: 4,
                                                    minLines: 1,
                                                    style: TextStyle(
                                                      fontSize: 10,
                                                      color: Colors.white
                                                    ),
                                                    decoration: InputDecoration(
                                                      suffixIcon: IconButton(
                                                        icon: Icon(Icons.comment),
                                                        iconSize: 15,
                                                        color: Colors.white,
                                                        onPressed: () {},
                                                      ),
                                                      labelText: '请输入评论，最多50',
                                                      labelStyle: TextStyle(color: Colors.white),
                                                        border: OutlineInputBorder(
                                                          borderSide: BorderSide(
                                                            color: Colors.white.withOpacity(0.5),  // 边框颜色
                                                          ),
                                                        ),
                                                        enabledBorder: OutlineInputBorder(
                                                          borderSide: BorderSide(
                                                            color: Colors.white.withOpacity(0.3),  // 边框颜色
                                                          ),
                                                        ),
                                                        // filled: true,  // 不然 fillColor 等 不生效
                                                        // fillColor: Colors.white.withOpacity(0.6),
                                                        // focusColor: Colors.white.withOpacity(0.5),
                                                        // hoverColor: Colors.white.withOpacity(0.3),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        )
                                    ),
                                  ],
                                ),
                              )
                          ),
                        ),
                        Offstage(
                          offstage: commentShow,
                          child: Align(
                            alignment: Alignment.centerRight,
                            child: IconButton(
                              icon: Icon(Icons.comment),
                              color: Colors.blue,
                              onPressed: (){
                                setState(() {
                                  commentShow = !commentShow;
                                });},
                            ),
                          ),
                        ),
                        Offstage(
                          offstage: !boardShow,
                          child: Align(
                            alignment: Alignment.bottomCenter,
                            child: IconButton(
                              icon: Icon(Icons.brush),
                              color: Colors.blue,
                              onPressed: (){
                                setState(() {
                                  boardShow = !boardShow;
                                });},
                            ),
                          ),
                        ),
                        Offstage(
                          offstage: boardShow,
                          child: Align(
                            alignment: Alignment.bottomCenter,
                            child: Container(
                              color: Colors.black12,
                              height: 168,
                              child: Column(
                                children: [
                                  IconButton(
                                    icon: Icon(Icons.keyboard_arrow_down),
                                    color: Colors.blue,
                                    onPressed: (){
                                      setState(() {
                                        boardShow = !boardShow;
                                      });},
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 10, right: 80, bottom: 20),
                                    child: Wrap(
                                      spacing: 5,
                                      runSpacing: 5,
                                      crossAxisAlignment: WrapCrossAlignment.center,
                                      children: <Widget>[
                                        buildInkWell(drawProvider, 5),
                                        buildInkWell(drawProvider, 8),
                                        buildInkWell(drawProvider, 10),
                                        buildInkWell(drawProvider, 15),
                                        buildInkWell(drawProvider, 17),
                                        buildInkWell(drawProvider, 20),
                                        Padding(
                                            padding: EdgeInsets.only(left: 10, right: 10)),
                                        IconButton(
                                          icon: Icon(Icons.arrow_back),
                                          onPressed: () {
                                            _provider.undoDate(); //撤销一步
                                          },
                                        ),
                                        IconButton(
                                          icon: Icon(Icons.arrow_forward),
                                          onPressed: () {
                                            _provider.reverseUndoDate();  //反撤销
                                          },
                                        ),
                                        IconButton(
                                          icon: Icon(Icons.clear),
                                          onPressed: () {
                                            //清除
                                            _provider.clear();
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 10, right: 80, bottom: 20),
                                    child: Wrap(
                                      spacing: 5,
                                      runSpacing: 5,
                                      children: pintColor.keys.map((key) {
                                        Color value = pintColor[key];
                                        return InkWell(
                                          onTap: () {
                                            drawProvider.pentColor = key;
                                            drawProvider.notifyListeners();
                                          },
                                          child: Container(
                                            width: 32,
                                            height: 32,
                                            color: value,
                                            child: drawProvider.pentColor == key
                                                ? Icon(
                                              Icons.done,
                                              color: Colors.white,
                                            )
                                                : null,
                                          ),
                                        );
                                      }).toList(),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: () {
      //     setState(() {
      //       offstage = !offstage;
      //     });
      //   },
      //   tooltip: '显示底部',
      //   mini: true,
      //   child: Icon(Icons.menu),
      // ),
    );
  }

  InkWell buildInkWell(DrawProvider drawProvider, double size) {
    return InkWell(
      onTap: () {
        drawProvider.pentSize = size / 2;
        drawProvider.notifyListeners();
      },
      child: Container(
        width: 40,
        height: 40,
        child: Center(
          child: Container(
            decoration: new BoxDecoration(
              color: pintColor[drawProvider.pentColor],
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(size / 4)),
              //设置四周边框
              border: drawProvider.pentSize == size / 2
                  ? Border.all(width: 1, color: Colors.black)
                  : null,
            ),
            width: size / 2,
            height: size / 2,
          ),
        ),
      ),
    );
  }

  Widget _mediaView() {
    return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Container(
              decoration: new BoxDecoration(color: Colors.blue),
              child: ListTile(
                title: Text("文件列表"),
                leading: Icon(Icons.list),
              ),
            ),
            Expanded(
                child: ListView.builder(
                    itemCount: mediaList.length,
                    itemBuilder: (context, int index) {
                      String base64Str = 'data:image/jpeg;base64,' +
                          mediaList[index]["buffer"];
                      var image = Image.memory(
                        Base64Decoder().convert(base64Str.split(',')[1]),
                        height: 90,
                        width: 160,
                      );
                      // var icon = mediaList[index]["type"].split("/")[0] == "image" ? Icon(Icons.image) : Icon(Icons.videocam);
                      return SizedBox(
                        width: 300,
                        child: Row(
                          children: [
                            Padding(padding: EdgeInsets.all(3)),
                            Text((index + 1).toString()),
                            Container(
                              margin: EdgeInsets.all(10),
                              child: image,
                            ),
                            Expanded(
                                child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(
                                  height: 50,
                                  child: Text(mediaList[index]["name"]),
                                ),
                                SizedBox(
                                  height: 40,
                                  child: ListTile(
                                    title: Text(mediaList[index]["userName"]),
                                    contentPadding: EdgeInsets.only(right: 10),
                                    trailing: Icon(
                                      Icons.delete,
                                      size: 15,
                                    ),
                                  ),
                                )
                              ],
                            )),
                          ],
                        ),
                      );
                    }))
          ],
        ));
  }

  Future<dynamic> getReview() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String reviewId = prefs.getString("reviewId");
    try {
      Response response =
          await dio.post(Config.BASE_URL + "/review/getReview", data: {
        "reviewId": reviewId,
      });
      mediaIdList = response.data["mediaId"];

      var response2 = await dio.post(Config.BASE_URL + "/media/getReviewMedia",
          data: {"id": mediaIdList});
      mediaList = response2.data;

      var response3 = await dio.get(
        Config.BASE_URL + "/comment/getComment",
        queryParameters: {
          "mediaId": mediaIdList[0],
        },
      );
      comments = response3.data;
      print(comments);

      var response4 = await dio.get(
        Config.BASE_URL + "/media/picture/getPicture",
        queryParameters: {
          "fileId": mediaList[0]["fileId"],
          "type": mediaList[0]["type"].split('/')[1]
        },
        options: Options(
          responseType: ResponseType.stream,
        ),
        onReceiveProgress: (num received, num total) {
          double _process = double.parse('${(received / total).toStringAsFixed(2)}');/// 获取下载进度
          print(_process);
        },
      );
      // print(response4.data);
      final stream = await (response4.data as ResponseBody).stream.toList();
      final result = BytesBuilder();
      for (Uint8List subList in stream) {
        result.add(subList);
      }
      img = result.takeBytes();

      return 1;
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
    _provider.connect();
    getReview().then((data) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _provider.dispose();
    super.dispose();
  }
}
